<template>
  <!-- 在线率监控 -->
  <div class="onlineRateContent">
    <div class="contentLayout">
      <!-- 左侧图表区域 -->
      <div class="chartSection">
        <div class="chartItem">
          <div
            class="chartContainer"
            id="onlineChart"
            :style="{
              width: `${pieHeight}px`,
            }"
          ></div>
        </div>
        <div class="chartItem">
          <div
            class="chartContainer"
            id="offlineChart"
            :style="{
              width: `${pieHeight}px`,
            }"
          ></div>
        </div>
      </div>

      <!-- 右侧表格区域 -->
      <div class="tableWrapper">
        <!-- 在线详情 -->
        <div class="tableSection">
          <div class="sectionTitle">在线详情</div>
          <a-table
            :dataSource="onlineTableData"
            :columns="onlineColumns"
            size="small"
            :pagination="false"
            :scroll="{ x: 'max-content', y: tableHeight - 100 }"
            bordered
          >
          </a-table>
        </div>

        <!-- 离线详情 -->
        <div class="tableSection">
          <div class="sectionTitle">离线详情</div>
          <a-table
            :dataSource="offlineTableData"
            :columns="offlineColumns"
            size="small"
            :pagination="false"
            :scroll="{ x: 'max-content', y: tableHeight - 150 }"
            bordered
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'downloadTime'">
                {{ record.downloadTime }}
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 
import * as echarts from "echarts"
import { onlineChartOption, offlineChartOption } from "./chartOption"


const $api = inject("$api")

// 图表实例
let onlineChartInstance = null
let offlineChartInstance = null

// 在线表格数据
const onlineTableData = ref([])
const onlineColumns = [
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 120,
    align: "center",
  },
  {
    title: "电源柜名称",
    dataIndex: "equipName",
    key: "equipName",
    width: 120,
    align: "center",
  },
  {
    title: "容量",
    /* dataIndex: "singleCapacity",
    key: "singleCapacity", */
    width: 100,
    align: "center",
    customRender: ({ record }) => {
      return record.singleCapacity
        ? (record.singleCapacity / 1000).toFixed(3)
        : "--"
    },
  },
]
// 离线表格数据
const offlineTableData = ref([])
const offlineColumns = [
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 120,
    align: "center",
  },
  {
    title: "电源柜名称",
    dataIndex: "equipName",
    key: "equipName",
    width: 120,
    align: "center",
  },
  {
    title: "容量",
    width: 100,
    align: "center",
    customRender: ({ record }) => {
      return record.singleCapacity
        ? (record.singleCapacity / 1000).toFixed(3)
        : "--"
    },
  },
  {
    title: "下线时间",
    dataIndex: "offTime",
    key: "offTime",
    width: 160,
    align: "center",
  },
]
//获取表格
const getOnlineDataTable = async () => {
  try {
    // 模拟数据，实际项目中应该调用API
    let res = await $api.equipStatusDetail()
    if (res && res.code === 0) {
      onlineTableData.value = res.data.onlineDetails
      offlineTableData.value = res.data.offDetails
    }
  } catch (error) {
    message.error("获取在线数据失败")
    console.error(error)
  }
}

// 初始化图表
const initCharts = () => {
  // 初始化离线功率图表

  // 窗口大小变化时重新调整图表大小
  window.addEventListener("resize", handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  onlineChartInstance && onlineChartInstance.resize()
  offlineChartInstance && offlineChartInstance.resize()
}

// 获取在线设备数据
const optionData = ref({})
const numData = ref([])
const capData = ref([])
const getOnlineData = async () => {
  try {
    // 模拟数据，实际项目中应该调用API
    let res = await $api.equipStatusStatistics()
    if (res && res.code === 0) {
      optionData.value = res.data
    }
    numData.value = []
    capData.value = []

    let list = []
    if (res.data.online !== 0 && res.data.offline !== 0) {
      list.push(
        {
          name: "在线数量",
          value: res.data.online,
          percent: (res.data.online / res.data.linkCount).toFixed(2),
        },
        {
          name: "离线数量",
          value: res.data.offline,
          percent: (res.data.offline / res.data.linkCount).toFixed(2),
        }
      )
      list.forEach((item) => {
        numData.value.push({ value: item.value, name: item.name })
        numData.value.push({
          name: "",
          value: res.data.linkCount / 100,
          itemStyle: { color: "transparent" },
        })
      })
    } else {
      if (res.data.offline === 0) {
        list.push({
          name: "在线数量",
          value: res.data.online,
          percent: (res.data.online / res.data.linkCount).toFixed(2),
        })
        list.forEach((item) => {
          numData.value.push({ value: item.value, name: item.name })
        })
      }
      if (res.data.online === 0) {
        list.push({
          name: "离线数量",
          value: res.data.offline,
          percent: (res.data.offline / res.data.linkCount).toFixed(2),
        })
        list.forEach((item) => {
          numData.value.push({ value: item.value, name: item.name })
        })
      }
    }

    let caplist = []
    if (res.data.offlineCap !== 0 && res.data.onlineCap !== 0) {
      res.data.offlineCap = res.data.offlineCap / 1000
      res.data.onlineCap = res.data.onlineCap / 1000
      res.data.totalCap = (res.data.offlineCap + res.data.onlineCap) / 1000
      caplist.push(
        {
          name: "在线容量",
          value: res.data.onlineCap.toFixed(2),
          percent: (res.data.onlineCap / res.data.totalCap).toFixed(2),
        },
        {
          name: "离线容量",
          value: res.data.offlineCap.toFixed(2),
          percent: (res.data.offlineCap / res.data.totalCap).toFixed(2),
        }
      )
      caplist.forEach((item) => {
        capData.value.push({ value: item.value, name: item.name })
        capData.value.push({
          name: "",
          value: 0.05,
          itemStyle: { color: "transparent" },
        })
      })
    } else {
      if (res.data.offlineCap === 0) {
        caplist.push({
          name: "在线容量",
          value: res.data.onlineCap.toFixed(2),
          percent: (res.data.onlineCap / res.data.totalCap).toFixed(2),
        })
        caplist.forEach((item) => {
          capData.value.push({ value: item.value, name: item.name })
        })
      }
      if (res.data.onlineCap === 0) {
        caplist.push({
          name: "离线容量",
          value: res.data.offlineCap.toFixed(2),
          percent: (res.data.offlineCap / res.data.totalCap).toFixed(2),
        })
        caplist.forEach((item) => {
          capData.value.push({ value: item.value, name: item.name })
        })
      }
    }
    setTimeout(() => {
      numPieInit()
      capPieInit()
    }, 500)
    // 更新在线图表数据
  } catch (error) {
    message.error("获取在线数据失败")
    console.error(error)
  }
}

const numPieInit = async () => {
  const { series, title } = onlineChartOption
  title.text = `${optionData.value.linkCount}个` || "--"
  title.textStyle.fontSize = pieHeight.value > 320 ? "30" : "24"
  series[0].data = numData.value
  series[1].data = numData.value
  // 初始化在线率图表
  const onlineChartDom = document.getElementById("onlineChart")
  onlineChartInstance = echarts.init(onlineChartDom)
  onlineChartInstance.setOption(onlineChartOption)
}

const capPieInit = async () => {
  const { series, title } = offlineChartOption
  series[0].data = []
  series[1].data = []
  optionData.value.totalCap =
    optionData.value.offlineCap + optionData.value.onlineCap
  title.text = `${optionData.value.totalCap.toFixed(2)}MW` || "--"
  title.textStyle.fontSize = pieHeight.value > 320 ? "30" : "24"
  series[0].data = capData.value
  series[1].data = capData.value
  console.log(capData.value)
  const offlineChartDom = document.getElementById("offlineChart")
  offlineChartInstance = echarts.init(offlineChartDom)
  offlineChartInstance.setOption(offlineChartOption)
}
//设置表格最高高度
const pieHeight = computed(() => {
  // 定义动态表格-格式
  return window.innerHeight / 2 - 85
})
const tableHeight = computed(() => {
  // 定义动态表格-格式
  return window.innerHeight / 2 - 50
})
// 页面加载时初始化
onMounted(() => {
  nextTick(() => {
    initCharts()
    getOnlineData()
    getOnlineDataTable()
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  window.removeEventListener("resize", handleResize)
  onlineChartInstance && onlineChartInstance.dispose()
  offlineChartInstance && offlineChartInstance.dispose()
})
</script>

<style lang="less" scoped>
.onlineRateContent {
  padding: 16px;
  background-color: #0d1117;
  color: #fff;
  height: calc(100vh - 130px);
}

.contentLayout {
  display: flex;
  gap: 20px;
  height: 100%;
}

.chartSection {
  flex: 0 0 500px;
  display: flex;
  flex-direction: column;
  gap: 0;

  .chartItem {
    flex: 1;
    display: flex;
    justify-content: center;

    .chartContainer {
      width: 100%;
      height: 100%;
      min-height: 300px;
    }
  }
}

.tableWrapper {
  flex: 1;
  min-width: 0;
  overflow: auto;
}

.tableSection {
  margin-bottom: 20px;

  .sectionTitle {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
  }
}

:deep(.ant-table) {
  background-color: transparent;
  color: #fff;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #1a2233;
  color: #fff;
  border-color: #303b4d;
}

:deep(.ant-table-tbody > tr > td) {
  background-color: #0d1117;
  color: #fff;
  border-color: #303b4d;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #1a2233;
}
</style>
